package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.vos.HotArticleVo;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl  implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;



    /**
     * 加载首页
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto,Integer type) {
        //1.参数校验
        if(dto.getSize()==null){
            dto.setSize(10);
        }
        if(dto.getTag()==null){
            dto.setTag("__all__");
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }


        //2.调用mapper接口
        List<ApArticle> articleList = apArticleMapper.load(dto, type);

        //3.封装数据
        return   ResponseResult.okResult(articleList);
    }

    /**
     * 新增文章三剑客
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
//    @Async
    public ResponseResult saveAparticle(ArticleDto dto) {
        ApArticle apArticle=new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        //1.判断是否保存还是修改
        if(dto.getId()==null){
            //如果保存的话
            //新增ap_article
            apArticle.setCreatedTime(new Date());
            apArticle.setPublishTime(new Date());
            apArticleMapper.insert(apArticle);
            //新增ap_article_config
            ApArticleConfig aparticleConfig=new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(aparticleConfig);
            //新增ap_article_content
            ApArticleContent apArticleContent=new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //如果是修改的话
            //修改ap_article
            apArticleMapper.updateById(apArticle);
            //修改ap_article_content
            ApArticleContent apArticleContent=apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
            if(apArticleContent!=null){
                apArticleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(apArticleContent);
            }
        }


        //异步调用生成静态文件
        generatorHtml(apArticle.getId());

        //发送消息道kafka中



        //返回一个文章id，把该articleId写入wmnews表中
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 文章列表查询plus，首页
     *
     * @param dto
     * @return
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 文章列表查询plus.查询的就是首页
     *
     * @param dto ,推荐频道  __all__  如果其他频道则是id
     * @param
     * @return
     */
    @Override
    public ResponseResult loadArticleList2(ArticleHomeDto dto) {
        String hotArticleListStr = stringRedisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        //转化类型
        List<HotArticleVo> hotArticleVoList = JSONArray.parseArray(hotArticleListStr, HotArticleVo.class);

        return ResponseResult.okResult(hotArticleVoList);
    }


    /**
     * 抽取生成静态文件并保存道到minio中
     * @param id
     */
    private void generatorHtml(Long id) {
        //1.根据id获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, id));
        if (apArticleContent==null){
            return;
        }
        //2.生成html文件
        Template template = null;
        try {
            template = configuration.getTemplate("article.ftl");

            //获取数据类型
            Map dataModel =new HashMap<>();
            dataModel.put("conten", JSONArray.parseArray(apArticleContent.getContent()));
            //合成
            StringWriter out =new StringWriter();
            template.process(dataModel,out);

            //3.上传文件到minIo中
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            //4.修改ap_article 表中url字段
            ApArticle apArticle = apArticleMapper.selectById(apArticleContent.getArticleId());
            if (apArticle!=null){
                apArticle.setStaticUrl(path);
                apArticleMapper.updateById(apArticle);
            }
            //发送消息，创建索引
            createArticleESIndex(apArticle,apArticleContent.getContent(),path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 送消息，创建索引
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }

}
